package cn.bugstack.gateway.session;

import cn.bugstack.gateway.bind.GenericReferenceRegistry;
import cn.bugstack.gateway.bind.IGenericReference;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.service.GenericService;

import java.util.HashMap;
import java.util.Map;

/*
 * 配置类 RPC服务的配置信息
 */
public class Configuration {
    public Configuration() {
        // TODO 后期从配置中获取
        ApplicationConfig application = new ApplicationConfig();
        application.setName("api-gateway-test");
        application.setQosEnable(false);

        RegistryConfig registry = new RegistryConfig();
        registry.setAddress("zookeeper://192.168.1.105:2181?timeout=200000");
        registry.setRegister(false);

        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setInterface("cn.bugstack.gateway.rpc.IActivityBooth");
        reference.setVersion("1.0.0");
        reference.setGeneric("true");

        applicationConfigMap.put("api-gateway-test", application);
        registryConfigMap.put("api-gateway-test", registry);
        referenceConfigMap.put("cn.bugstack.gateway.rpc.IActivityBooth", reference);
    }


    // RPC 应用服务配置，RPC 注册中心配置，RPC 泛化服务配置
    private final Map<String, ApplicationConfig> applicationConfigMap = new HashMap<>();
    private final Map<String, RegistryConfig> registryConfigMap = new HashMap<>();
    private final Map<String, ReferenceConfig<GenericService>> referenceConfigMap = new HashMap<>();
    // 所有的被调用的接口，都通过泛化调用的方式，调用服务

    // 通过应用名字 获取应用配置
    public ApplicationConfig getApplicationConfig(String applicationName) {
        return applicationConfigMap.get(applicationName);
    }

    public RegistryConfig getRegistryConfig(String applicationName) {
        return registryConfigMap.get(applicationName);
    }

    // 通过接口名字，获取泛化调用服务
    public ReferenceConfig<GenericService> getReferenceConfig(String interfaceName) {
        return referenceConfigMap.get(interfaceName);
    }


    // 通过当前配置，构造绑定方法、获取服务的类，依赖注入
    private final GenericReferenceRegistry registry = new GenericReferenceRegistry(this);

    // 通过构造的类，获取、添加代理类
    public void addApplicationConfig(String applicationName, String interfaceName, String methodName) {
        registry.addGenericReference(applicationName, interfaceName, methodName);
    }

    public IGenericReference getGenericReference(String methodName) {
        return registry.getGenericReference(methodName);
    }

}
